package com.xiqi.commons.redis.serializer;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Optional;

/**
 * @program: commonsredis
 * @description:
 * @author: Shine
 * @create: 2019-08-01 11:08
 */
@Component
public class MyRedisSerializer implements RedisSerializer {

    /**
     * @Author: Shine
     * @Date: 19-8-1 上午11:13
     * @Description: 序列化
     * @Param: [o]
     * @return: byte[]
     */
    @Override
    public byte[] serialize(Object o) throws SerializationException {
        if (o == null) {
            return null;
        }
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(o);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @Author: Shine
     * @Date: 19-8-1 上午11:13
     * @Description: 反序列化
     * @Param: [bytes]
     * @return: java.lang.Object
     */
    @Override
    public Object deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null) {
            return null;
        }
        try {

            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

            return objectInputStream.readObject();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
